package com.freeter.modules.wiztalk.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.freeter.common.util.UuidUtil;
import com.freeter.common.utils.MPUtil;
import com.freeter.common.utils.PageUtils;
import com.freeter.common.utils.R;
import com.freeter.common.validator.ValidatorUtils;
import com.freeter.modules.wiztalk.entity.*;
import com.freeter.modules.wiztalk.entity.model.ReportCrashModel;
import com.freeter.modules.wiztalk.entity.model.ReportDataModel;
import com.freeter.modules.wiztalk.entity.model.ReportTrackModel;
import com.freeter.modules.wiztalk.entity.vo.ReportTrackVO;
import com.freeter.modules.wiztalk.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;


/**
 *
 *api接口
 * @author Arial
 * @email Arial@foxmail.com
 * @date 2018-09-05 15:53:27
 */
@RestController
@RequestMapping("mobile/reportTrack")
@Api(tags="wiztalk接口")
public class ReportTrackController {
    @Autowired
    private ReportTrackService reportTrackService;
    @Autowired
    private ReportStartService reportStartService;
    @Autowired
    private ReportLoginService reportLoginService;
    @Autowired
    private ReportErrorService reportErrorService;
    @Autowired
    ReportErrorSubService reportErrorSubService;
	 /**
     * 列表
     */
    @GetMapping("/page")
    public R page(@RequestParam Map<String, Object> params, ReportTrackModel reportTrackModel){

        EntityWrapper< ReportTrackEntity> ew = new EntityWrapper< ReportTrackEntity>();
        ReportTrackEntity reportTrack = new  ReportTrackEntity( reportTrackModel);
     	ew.allEq(MPUtil.allEQMapPre( reportTrack, "reportTrack"));
    	PageUtils page = reportTrackService.queryPage(params, ew);
        return R.ok().put("data",  page.getList());

    }



    /**
     * 查询
     */
    @GetMapping("/list")
    public R list(ReportTrackModel reportTrackModel){
		ValidatorUtils.validateEntity(reportTrackModel);
        EntityWrapper< ReportTrackEntity> ew = new EntityWrapper< ReportTrackEntity>();
		ReportTrackEntity reportTrack = new  ReportTrackEntity( reportTrackModel);
     	ew.allEq(MPUtil.allEQMapPre( reportTrack, "reportTrack"));
		List<ReportTrackVO>  reportTrackVOList =  reportTrackService.selectListVO(ew);
		return R.ok("查询成功").put("data", reportTrackVOList);
    }

	 /**
     * 查询
     */
    @GetMapping("/query")
    public R query(ReportTrackModel reportTrackModel){
		ValidatorUtils.validateEntity(reportTrackModel);
        EntityWrapper< ReportTrackEntity> ew = new EntityWrapper< ReportTrackEntity>();
		ReportTrackEntity reportTrack = new  ReportTrackEntity( reportTrackModel);
		ew.allEq(MPUtil.allEQMapPre( reportTrack, "reportTrack"));
		ReportTrackVO reportTrackVO =  reportTrackService.selectVO(ew);
		return R.ok("查询成功").put("data",  reportTrackVO);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation("获取相应的")
    public R info(@PathVariable("id") String id){
        ReportTrackEntity reportTrack = reportTrackService.selectById(id);

        return R.ok().put("reportTrack", reportTrack);
    }

    /**
     * 保存
     */
    @PostMapping("/save/json")
    @ApiOperation("埋点信息上报")
    public R saveJson(@RequestBody ReportDataModel reportTrack){
        Date reachTime = new Date();
        String clientData =reportTrack.getClientData();
        List<ReportTrackEntity> reportTrackEntityList = new ArrayList<ReportTrackEntity>();
        List<ReportLoginEntity> reportLoginEntityList = new ArrayList<ReportLoginEntity>();
        List<ReportStartEntity> reportStartEntityList = new ArrayList<ReportStartEntity>();
        List<ReportTrackEntity> clientList = com.alibaba.fastjson.JSONObject.parseArray(clientData, ReportTrackEntity.class);
        for (Iterator iterator = clientList.iterator(); iterator.hasNext();) {
            ReportTrackEntity reportTrackEntity = (ReportTrackEntity) iterator.next();
            String type=reportTrackEntity.getType();
            if ("event".equalsIgnoreCase(type)) {
                reportTrackEntity.setReachTime(reachTime);
                ValidatorUtils.validateEntity(reportTrackEntity);
                reportTrackEntityList.add(reportTrackEntity);
            }else if("login".equalsIgnoreCase(type)){
                ReportLoginEntity reportLoginEntity = new ReportLoginEntity();
                reportTrackEntity.setReachTime(reachTime);
                BeanUtils.copyProperties(reportTrackEntity, reportLoginEntity);
                reportLoginEntityList.add(reportLoginEntity);
            }else if("start".equalsIgnoreCase(type)){
                ReportStartEntity reportStartEntity = new ReportStartEntity();
                reportTrackEntity.setReachTime(reachTime);
                 BeanUtils.copyProperties(reportTrackEntity, reportStartEntity);
                reportStartEntityList.add(reportStartEntity);
            }
        }
        if (!reportTrackEntityList.isEmpty()){
//            reportTrackService.insertBatch(reportTrackEntityList);
              reportTrackService.batchInsert(reportTrackEntityList);
        }
        if (!reportLoginEntityList.isEmpty()){
            reportLoginService.insertBatch(reportLoginEntityList);
        }
        if (!reportStartEntityList.isEmpty()){
            reportStartService.insertBatch(reportStartEntityList);
        }
        return R.ok();
    }


    @PostMapping("/save/error")
    @ApiOperation("错误信息上报")
    public R uplaodFile(ReportErrorEntity reportError, @RequestParam("files") MultipartFile file, HttpServletRequest request) {
        String text="";
       // String clientData =reportTrack.getClientData();
        if (file != null && file.getSize() > 0) {
            try {
                byte [] buffer=file.getBytes();
                text=new String(buffer,"utf-8");

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            reportError.setId(UUID.randomUUID().toString());
            reportError.setReachTime(new Date());
             ValidatorUtils.validateEntity(reportError);
             reportErrorService.insert(reportError);
             if (StringUtils.isNotEmpty(text)){
                 ReportErrorSubEntity errorSubEntity = new ReportErrorSubEntity();
                 errorSubEntity.setId(reportError.getId());
                 errorSubEntity.setText(text);
                 reportErrorSubService.insert(errorSubEntity);
             }

        return R.ok();
    }

    @PostMapping("/save/crash")
    @ApiOperation("崩溃日志上报")
    public R uplaodCrash(@RequestBody ReportCrashModel reportCrashModel ) {
        String text =reportCrashModel.getText();
        String clientData=reportCrashModel.getClientData();

        List<ReportErrorEntity> clientList = com.alibaba.fastjson.JSONObject.parseArray(clientData, ReportErrorEntity.class);
        if (!clientList.isEmpty()) {
            ReportErrorEntity reportError = clientList.get(0);
            reportError.setId(UUID.randomUUID().toString());
            reportError.setReachTime(new Date());
            ValidatorUtils.validateEntity(reportError);
            reportErrorService.insert(reportError);
            if (StringUtils.isNotEmpty(text)) {
                ReportErrorSubEntity errorSubEntity = new ReportErrorSubEntity();
                errorSubEntity.setId(reportError.getId());
                errorSubEntity.setText(text);
                reportErrorSubService.insert(errorSubEntity);
            }
        }
        return R.ok();
    }


    /**
     * 保存
     */
    @PostMapping("/save/form")
    public R saveForm(@RequestParam("files") MultipartFile file){
        if (file != null && file.getSize() > 0) {

            // 上传文件
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
            //category.setIcon(url);
        }
        // categoryService.updateById(category);
     //   ValidatorUtils.validateEntity(reportError);
       // reportErrorService.insert(reportError);
        return R.ok();
    }




    /**
     * 修改（参数：json）
     */
    @PostMapping("/update/json")
    @ApiOperation("修改数据（参数：json格式）")
    public R updateJson(@RequestBody ReportTrackEntity reportTrack){
        ValidatorUtils.validateEntity(reportTrack);
        reportTrackService.updateAllColumnById(reportTrack);//全部更新

        return R.ok();
    }


    /**
     * 修改（参数：传统表单）
     */
    @PostMapping("/update/form")
    @ApiOperation("修改数据（参数：表单格式）")
    public R updateForm(ReportTrackEntity reportTrack){
        ValidatorUtils.validateEntity(reportTrack);
        reportTrackService.updateAllColumnById(reportTrack);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation("删除数据")
    public R delete(@RequestBody String[] ids){
        reportTrackService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

}
